var Mqtt = require( "mqtt" )

//var  mqtt = Mqtt.connect( "mqtt://111.231.108.101"  )

var  mqtt = Mqtt.connect( "mqtt://127.0.0.1"  )

mqtt.on( "connect" , ()=> {
    console.log( "connect success !!!" );

    mqtt.subscribe( "filter/#" )
    mqtt.subscribe( "queryDevice" );

    //setTimeout( ()=> { mqtt.publish( "wangsheng/test" , "xxxxxx" );}, 100);
});

mqtt.on( "error", ( error )=> {
  console.log( "error: " , error );
});

function dump( buffer ) {
  for( let i = 0; i < buffer.length; i++ ) {
    console.log( buffer.toString( 'hex' )  )
  }
}

var all_devices = {}

mqtt.on( "message" , ( topic, payload, packet )=> {

try{

  if( topic == "queryDevices" ) {
      mqtt.publish( "monitor/devices", JSON.stringify( all_devices ) );
  }

  var topic = topic.split( "/" )
  var mac = topic[2]
  var ip = topic[ 1]
  //console.log( "device message: " , payload.toString() )
  console.log("----------------------------------------------------" )
  console.log( "ip: ", ip, " mac: ", mac )
  var data = payload

  if( all_devices[mac] === undefined ) {
      all_devices[mac] = { arm_areas: {}, isBufang: false }
      mqtt.publish( "start/" + ip + "/" + mac, JSON.stringify( { msg: "new device started" }  ) );

  }

  var device = all_devices[mac];

  for (let offset = 0; offset < data.length;  )  {
	var firstB = data[offset]
	if ( (firstB >> 4) == 7 ) {
      console.log("键盘消息")
      var line1 = data.slice( offset + 3, offset + 3 + 16 ).toString( "ascii" );
      var line2 = data.slice( offset + 21, offset + 21+16 ).toString( "ascii" );

      console.log( ">", line1 )
      console.log( ">", line2 )
      //console.log( "#", data.slice( offset + 3,  offset + 3 + 16 ) .toString( 'hex' ) )
      //keboard display message
      //console.log( "#", data.slice( offset + 21,  offset + 21 + 16 ) .toString( 'hex' ) )
      offset += 39


      var matched = line1.match(  /Alarm ([0-9]+)/ );
      if( matched ) {

          var arm_area_idx = Number( matched[1] );
          console.log( arm_area_idx , "号防区报警" )
	      if( device.arm_areas[arm_area_idx] == undefined ) {
			device.arm_areas[arm_area_idx] = {};
	      }

          var old_alarm_time = device.arm_areas[arm_area_idx].a  || 0;
          console.log( "old_alarm_time: ", old_alarm_time );

          if( Date.now() - old_alarm_time >  ( 3 * 1000 )) {

		    console.log( "device ",  mac, " alarm at : ", arm_area_idx );
            mqtt.publish( "monitor/" + ip + "/" + mac + "/alarm" , JSON.stringify( { [arm_area_idx]: "alarm" }  ) )
            device.arm_areas[arm_area_idx].a = Date.now();
            device.arm_areas[arm_area_idx].s = "b";
            device.isBufang =  true;

          }
      }

      matched = line1.match( /Bypass ([0-9]+)/ );
      if( matched ) {
              var arm_area_idx = Number( matched[1] );

	      if( device.arm_areas[arm_area_idx] == undefined ) {
			device.arm_areas[arm_area_idx] = {};
	      }

          console.log( arm_area_idx , "号防区旁路" )
          mqtt.publish( "monitor/" + ip + "/" + mac + "/panglu" , JSON.stringify( { [arm_area_idx]: "bypass" }  ) )
          device.arm_areas[arm_area_idx].s = "c"
      }

      matched = line1.match( /Not Ready ([0-9]+)/ );

      if( matched ) {
          var arm_area_idx = Number( matched[1] );

	      if( device.arm_areas[arm_area_idx] == undefined ) {
			device.arm_areas[arm_area_idx] = {};
	      }
          console.log( arm_area_idx , "号防区Not ready" )
          mqtt.publish( "monitor/" + ip + "/" + mac + "/notReady" , JSON.stringify( { [arm_area_idx]: "notReady" }  ) )
          device.arm_areas[arm_area_idx].s = "c"
          device.isBufang = false
      }
    }
    else if (( firstB >> 4) == 2) {
        var b1 = data[offset+1]
        var b2 = data[offset+2]
        if ( b1 == 0x32 && b2 == 0 ){
            //报警消息 0x21 32 00
            console.log("无声报警消息")
            var b3 = data[ offset + 3 ]
            if( b3 == 0x24  ) {
            }
            else if( b3 == 0  ) {
            }
            else {
                console.log( "报警消息　分析不全" )
            }
            data.slice( offset, offset + 5 ).toString( 'hex' )

        }
        else if( (b1 ==0x36 || b1 == 0x37 ) && b2 == 0 ) {
            //报警消息 0x2* 36/37 00
            console.log( "unknown message " )
            data.slice( offset, offset + 5 ).toString( 'hex' )
        }
        else if( b1 == 0x33 && b2 == 0 ) {
            //设防消息 0x21 33 00
            var b3 = data[ offset + 3]
            if( b3 == 0x23 ) {
                console.log( "刚刚设防" )
            }
            else if( b3 == 0x20 ) {
              console.log( "已经设防" )
            }
            else {
              console.log( "不能识别的设防消息", data.slice( offset ))
            }

        }else if( ( b1 == 0x14  ||  b1 == 0x34) && b2 == 0 ) {
            // 0x21 14/34 00
            //待机消息也就是撤防状态
            console.log( "撤防状态" )
        }
        else if( ( b1==0x3c ) && b2 == 0 ) {
            console.log( "旁路信号" );
        }
        else if( (b1==0x30 ) && b2 == 0 ) {
            console.log( "撤防状态" )
        }
        else{
            console.log( "不能识别的 2x 消息" )
            console.log( data.slice( offset, offset + 5 ).toString( 'hex' ) )
        }

        console.log( data.slice( offset, offset + 5 ).toString( 'hex' ) )

        offset += 5
    } else if ( (firstB >> 4) == 8 ){
        //设防确认消息
        console.log("设防确认")
        offset += 3
    } else if ((firstB >> 4) == 0x1 ) {
	    offset += 1;
    } else {
        console.log("------ unknown message at offset : ", offset)
        console.log( data.slice( 0 ,  data.length ).toString( 'hex' ) )
        offset = data.length
    }
  }
}
catch( error ){
    console.log( "filter message error: ", error );
}

});



